home *** CD-ROM | disk | FTP | other *** search
/ Total Network Tools 2002 / NextStepPublishing-TotalNetworkTools2002-Win95.iso / Archive / Misc Servers / Zope.exe / BBB.PY < prev    next >
Encoding:
Text File  |  1999-08-16  |  12.7 KB  |  405 lines

  1. ##############################################################################
  2. # Zope Public License (ZPL) Version 1.0
  3. # -------------------------------------
  4. # Copyright (c) Digital Creations.  All rights reserved.
  5. # This license has been certified as Open Source(tm).
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions are
  8. # met:
  9. # 1. Redistributions in source code must retain the above copyright
  10. #    notice, this list of conditions, and the following disclaimer.
  11. # 2. Redistributions in binary form must reproduce the above copyright
  12. #    notice, this list of conditions, and the following disclaimer in
  13. #    the documentation and/or other materials provided with the
  14. #    distribution.
  15. # 3. Digital Creations requests that attribution be given to Zope
  16. #    in any manner possible. Zope includes a "Powered by Zope"
  17. #    button that is installed by default. While it is not a license
  18. #    violation to remove this button, it is requested that the
  19. #    attribution remain. A significant investment has been put
  20. #    into Zope, and this effort will continue if the Zope community
  21. #    continues to grow. This is one way to assure that growth.
  22. # 4. All advertising materials and documentation mentioning
  23. #    features derived from or use of this software must display
  24. #    the following acknowledgement:
  25. #      "This product includes software developed by Digital Creations
  26. #      for use in the Z Object Publishing Environment
  27. #      (http://www.zope.org/)."
  28. #    In the event that the product being advertised includes an
  29. #    intact Zope distribution (with copyright and license included)
  30. #    then this clause is waived.
  31. # 5. Names associated with Zope or Digital Creations must not be used to
  32. #    endorse or promote products derived from this software without
  33. #    prior written permission from Digital Creations.
  34. # 6. Modified redistributions of any form whatsoever must retain
  35. #    the following acknowledgment:
  36. #      "This product includes software developed by Digital Creations
  37. #      for use in the Z Object Publishing Environment
  38. #      (http://www.zope.org/)."
  39. #    Intact (re-)distributions of any official Zope release do not
  40. #    require an external acknowledgement.
  41. # 7. Modifications are encouraged but must be packaged separately as
  42. #    patches to official Zope releases.  Distributions that do not
  43. #    clearly separate the patches from the original work must be clearly
  44. #    labeled as unofficial distributions.  Modifications which do not
  45. #    carry the name Zope may be packaged in any form, as long as they
  46. #    conform to all of the clauses above.
  47. # Disclaimer
  48. #   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
  49. #   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  50. #   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  51. #   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
  52. #   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  53. #   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  54. #   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  55. #   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  56. #   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  57. #   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  58. #   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  59. #   SUCH DAMAGE.
  60. # This software consists of contributions made by Digital Creations and
  61. # many individuals on behalf of Digital Creations.  Specific
  62. # attributions are listed in the accompanying credits file.
  63. ##############################################################################
  64. """Read and (re-)format BoboPOS 2 database files
  65. """
  66.  
  67. import struct, string, sys, time, os
  68.  
  69. try: from cStringIO import StringIO
  70. except: from StringIO import StringIO
  71.  
  72. ppml=None
  73.  
  74. file__version__=3.0
  75. packed_version='SDBMV'+struct.pack(">f",file__version__)
  76.  
  77. def error(message, fatal=0, exc=0):
  78.     if exc:
  79.         sys.stderr.write('%s: %s' % (sys.exc_info()[0], sys.exc_info()[1]))
  80.     sys.stderr.write("\n%s\n" % message)
  81.     if fatal: sys.exit(fatal)
  82.  
  83. def _read_and_report(file, rpt=None, fromEnd=0, both=0, n=99999999, show=0,
  84.                      forgive=0, export=0):
  85.     """\
  86.     Read a file's index up to the given time.
  87.     """
  88.     first=1
  89.     seek=file.seek
  90.     read=file.read
  91.     unpack=struct.unpack
  92.     split=string.split
  93.     join=string.join
  94.     find=string.find
  95.     seek(0,2)
  96.     file_size=file.tell()
  97.     if not export:
  98.         seek(0)
  99.         h=read(len(packed_version))
  100.         if h != packed_version:
  101.             if h[:4]=='FS21':
  102.                 error("The input file is a ZODB File Storage\n"
  103.                       "This script only works with ZODB 2 (BoboPOS) "
  104.                       "data or export files."
  105.                       ,1)
  106.             else:
  107.                 error("The input file is not a ZODB 2 database file.\n"
  108.                       "This script only works with ZODB 2 (BoboPOS) "
  109.                       "data or export files."
  110.                       ,1)
  111.             
  112.     gmtime=time.gmtime
  113.  
  114.     if fromEnd: pos=file_size
  115.     else:       pos=newpos=(not export) and len(packed_version)
  116.      
  117.     tlast=0
  118.     err=0
  119.     tnamelast=None
  120.     while 1:
  121.         if fromEnd:
  122.             seek(pos-4)
  123.             l=unpack(">i", read(4))[0]
  124.             if l==0:
  125.                 b=pos
  126.                 p=pos-4
  127.                 while l==0:
  128.                     p=p-4
  129.                     seek(p)
  130.                     l=unpack(">i", read(4))[0]
  131.  
  132.                 pos=p+4
  133.                 error("nulls skipped from %s to %s" % (pos,b)) 
  134.             p=pos-l
  135.             if p < 0:
  136.                 error('Corrupted data before %s' % pos)
  137.                 if show > 0:
  138.                     p=pos-show
  139.                     if p < 0: p=0
  140.                     seek(p)
  141.                     p=read(pos-p)
  142.                 else:
  143.                     p=''
  144.                 error(p,1)
  145.             pos=p
  146.         else:
  147.             pos=newpos
  148.  
  149.         seek(pos)
  150.         h=read(24) # 24=header_size
  151.         if not h: break
  152.         if len(h) !=  24: break
  153.         oid,prev,start,tlen,plen=unpack(">iidii",h)
  154.         
  155.         if prev < 0 or (prev and (prev >= pos)):
  156.             error('Bad previous record pointer (%s) at %s' % (prev, pos))
  157.             if show > 0: error(read(show))
  158.             if not forgive:
  159.                 err=1
  160.                 break
  161.  
  162.         if start < tlast:
  163.             error('record time stamps are not chronological at %s' % pos)
  164.             if show > 0: error(read(show))
  165.             if not forgive:
  166.                 err=1
  167.                 break
  168.  
  169.         if plen > tlen or plen < 0 or oid < -999:
  170.             error('Corrupted data record at %s' % pos)
  171.             if show > 0: error(read(show))
  172.             err=1
  173.             break
  174.  
  175.  
  176.         newpos=pos+tlen
  177.         if newpos > file_size:
  178.             error('Truncated data record at %s' % pos)
  179.             if show > 0: error(read(show))
  180.             if not forgive:
  181.                 err=1
  182.                 break
  183.  
  184.         seek(newpos-4)
  185.         if read(4) != h[16:20]:
  186.             __traceback_info__=pos, oid,prev,start,tlen,plen
  187.             error('Corrupted data record at %s' % pos)
  188.             if show > 0:
  189.                 seek(pos+24)
  190.                 error(read(show))
  191.             err=1
  192.             break
  193.  
  194.         tlast=start-100
  195.  
  196.         if rpt is None: continue
  197.         n=n-1
  198.         if n < 1: break
  199.  
  200.         seek(pos+24)
  201.         if plen > 0:
  202.             p=read(plen)
  203.             if p[-1:] != '.': 
  204.                 error('Corrupted pickle at %s %s %s' % (pos,plen,len(p)))
  205.                 if show > 0:
  206.                     seek(pos+24)
  207.                     error(read(show))
  208.                 err=1
  209.                 break
  210.  
  211.         else: p=''
  212.         t=split(read(tlen-plen-28),'\t')
  213.         tname, user = (t+[''])[:2]
  214.         t=join(t[2:],'\t')
  215.         start,f=divmod(start,1)
  216.         y,m,d,h,mn,s=gmtime(start)[:6]
  217.         s=s+f
  218.         start="%.4d-%.2d-%.2d %.2d:%.2d:%.3f" % (y,m,d,h,mn,s)
  219.         rpt(pos,oid,start,tname,user,t,p,first,tname!=tnamelast)
  220.         first=0
  221.         tnamelast=tname
  222.  
  223.     if err and both and not fromEnd:
  224.         _read_and_report(file, rpt, 1, 0, n, show)
  225.  
  226.     rpt(None, None, None, None, None, None, None, None, None)
  227.  
  228.  
  229. def none(*ignored): pass
  230.  
  231. def positions(pos, *ignored): 
  232.     if pos is not None: sys.stdout.write("%s\n" % pos)
  233.  
  234. def oids(pos, oid, *ignored): 
  235.     if pos is not None: sys.stdout.write("%s\n" % oid)
  236.  
  237. def tab_delimited(*args):
  238.     sys.stdout.write("%s\n" % string.join(args[:6],'\t'))
  239.  
  240. def undo_log(pos, oid, start, tname, user, t, p, first, newtrans):
  241.     if not newtrans: return
  242.     
  243.     sys.stdout.write("%s:\t%s\t%s\t%s\n" % (pos, start, user, t))
  244.  
  245.         
  246. reports={
  247.     'none': (none,
  248.              ('Read a database file checking for errors',
  249.               'but producing no output')
  250.              ),
  251.     'oids': (oids,
  252.              ('Read the database and output object ids',)),
  253.     'positions': (positions,
  254.                   ('Read the database and output record positions',)),
  255.     'tab_delimited': (tab_delimited,
  256.                       ('Output record meta-data in tab-delimited format',)),
  257.  
  258.     'undo': (undo_log,
  259.              (
  260.                  'Output a transaction summary that shows the position of',
  261.                  'each transaction.  This is useful for undoing ',
  262.                  'transactions from the OS command line when',
  263.                  'some programming error has caused objects to get to',
  264.                  'a state where Zope can\'t start up.',
  265.                  '',
  266.                  'Eventually, there will be an undo utility for undoing',
  267.                  'individual transactions.  For now, you can simply',
  268.                  'truncate the file at the position of a problem',
  269.                  'transaction to return the database to the state it',
  270.                  'was in before the transaction',
  271.                  )),
  272.     }
  273.  
  274. def main(argv):
  275.     import getopt
  276.  
  277.     items=reports.items()
  278.     items.sort()
  279.     
  280.     usage="""Usage: python %s [options] filename
  281.  
  282.     where filename is the name of the database file.
  283.  
  284.     options:
  285.  
  286.        -r report
  287.  
  288.           Specify an output report.
  289.  
  290.           The valid reports are:\n\n\t\t%s
  291.  
  292.        -e
  293.  
  294.           Read the file from back to front
  295.  
  296.        -l n
  297.  
  298.           Show only n records
  299.  
  300.        -b
  301.  
  302.           If an error is encountered while reading from front,
  303.           ret reading from the back.
  304.  
  305.        -s n
  306.  
  307.           If a corrupted data record is found, show the first n
  308.           bytes of the corrupted record.
  309.  
  310.        -f filename
  311.  
  312.           Convert to ZODB 3 File-Storage format
  313.  
  314.        -p path
  315.  
  316.           Add a directory to the Python path.
  317.  
  318.        -x
  319.  
  320.           The input file is a ZODB 2 export file.
  321.  
  322.           
  323.     """ % (sys.argv[0],
  324.            string.join(map(
  325.                lambda i:
  326.                ("%s --\n\t\t\t%s" % (i[0], string.join(i[1][1],'\n\t\t\t'))),
  327.                items),
  328.                ',\n\n\t\t'))
  329.  
  330.     sys.path.append(os.path.split(sys.argv[0])[0])
  331.  
  332.     try:
  333.         opts, args = getopt.getopt(argv,'r:ebl:s:f:p:x')
  334.         filename,=args
  335.     except: error(usage,1,1)
  336.  
  337.     try: file=open(filename,'rb')
  338.     except: error('Coud not open %s' % filename,1,1)
  339.     
  340.     rpt=none
  341.     fromEnd=0
  342.     both=0
  343.     n=99999999
  344.     show=0
  345.     export=0
  346.     convert=0
  347.     for o, v in opts:
  348.         o=o[1:]
  349.         if o=='r':
  350.             try: rpt=reports[v][0]
  351.             except: error('Invalid report: %s' % v, 1)
  352.         elif o=='l':
  353.             try: n=string.atoi(v)
  354.             except: error('The number of records, %s, shuld ne an integer'
  355.                           % v, 1)
  356.         elif o=='s':
  357.             try: show=string.atoi(v)
  358.             except: error('The number of bytes, %s, shuld ne an integer'
  359.                           % v, 1)
  360.         elif o=='e': fromEnd=1
  361.         elif o=='x': export=1
  362.         elif o=='f': convert=1
  363.         elif o=='b': both=1
  364.         elif o=='p':
  365.             if v=='-':
  366.                 v=os.path.join(
  367.                     os.path.split(sys.argv[0])[0],
  368.                     '..','lib','python')
  369.             sys.path.insert(0,v)
  370.             print sys.path
  371.         else: error('Unrecognized option: -%s' % o, 1)
  372.  
  373.     if convert:
  374.         import FS
  375.         if export:
  376.             rpt=FS.ZEXP(v, file).rpt
  377.         else:
  378.             rpt=FS.FS(v, file).rpt
  379.  
  380.     _read_and_report(file, rpt, fromEnd, both, n, show,
  381.                      forgive=1, export=export)
  382.  
  383. if __name__=='__main__': main(sys.argv[1:])
  384.